package com.example.dell.newstart.search;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.dell.newstart.R;

import java.util.ArrayList;
import java.util.List;

/**
 * created by Dongkai on 2018/11/30
 * 自定义搜索控件，有 布局 和 逻辑的封装。
 */

public class CustomSearchView extends LinearLayout {
    private Context context;
    //private Button searchButton;
    private TextView deleteRecordTextView;
    private ListView record;
    private EditText searchEditText;
    private ImageView cleanIcon;

    private ShopDBHelper dbHelper;
    private boolean needToInsert = false;

    private List<String> keywordsList = new ArrayList<>();
    private KeywordsRecordAdapter keywordsRecordAdapter;

    public CustomSearchView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = getContext();
        LayoutInflater.from(context).inflate(R.layout.search_layout, this, true);
        initView();
        initEvent();
        dbHelper = new ShopDBHelper(context);
        keywordsRecordAdapter = new KeywordsRecordAdapter();
        record.setAdapter(keywordsRecordAdapter);
    }

    //定义的接口，在需要使用自定义搜索控件功能的时候，实现这个接口
    public interface OnSearchListener {
        void onSearch(String keywords);
    }

    private OnSearchListener onSearchListener;

    public void setOnSearchListener(OnSearchListener onSearchListener) {
        this.onSearchListener = onSearchListener;
    }


    private void initEvent() {
        SearchViewClickListener clickListener = new SearchViewClickListener();
        //searchButton.setOnClickListener(clickListener);
        cleanIcon.setOnClickListener(clickListener);
        deleteRecordTextView.setOnClickListener(clickListener);
        searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    querySearchRecord(s.toString());
                    cleanIcon.setVisibility(VISIBLE);
                }else {
                    cleanIcon.setVisibility(INVISIBLE);
                }

            }
        });
        searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String searchString = v.getText().toString().trim();
                if (TextUtils.isEmpty(searchString)) {
                    return false;
                }
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if(needToInsert){
                        insertWord(searchString);
                    }
                    if (onSearchListener != null) {
                        onSearchListener.onSearch(searchString);
                    } else {
                        Toast.makeText(context, "请设置搜索监听", Toast.LENGTH_SHORT).show();
                    }
                }
                return false;
            }
        });
        record.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (onSearchListener != null) {
                    Cursor item = (Cursor) parent.getItemAtPosition(position);
                    String keywords = item.getString(1);
                    onSearchListener.onSearch(keywords);
                } else {
                    Toast.makeText(context, "请设置搜索监听", Toast.LENGTH_SHORT).show();
                }
            }
        });
        record.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                return false;
            }
        });
    }

    private void initView() {
        //searchButton = findViewById(R.id.bt_search);
        deleteRecordTextView = findViewById(R.id.tv_delete);
        record = findViewById(R.id.lv_record);
        searchEditText = findViewById(R.id.et_search);
        cleanIcon = findViewById(R.id.iv_cancel);
        setRecordViewVisibility(false);
    }

    private class SearchViewClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
               // case R.id.bt_search:
                 //   String searchString = searchEditText.getText().toString().trim();
              //      if (!TextUtils.isEmpty(searchString)) {
              //          doSearch(searchString);
               //     } else {
             //           Toast.makeText(context, "搜索条件不能为空", Toast.LENGTH_SHORT).show();
             //       }
            //break;
                case R.id.iv_cancel:
                    searchEditText.setText("");
                    setRecordViewVisibility(false);
                    break;
                case R.id.tv_delete:
                    deleteAllRecord();
                    break;
            }
        }
    }

    //根据关键词搜索信息（触发搜索监听）
    private void doSearch(String searchString) {
        if (needToInsert) {
            insertWord(searchString);
        }
        if (onSearchListener != null) {
            onSearchListener.onSearch(searchString);
        } else {
            insertWord(searchString);
            Toast.makeText(context, "请设置搜索监听", Toast.LENGTH_SHORT).show();
        }

    }

    //删除所有历史记录
    private void deleteAllRecord() {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        database.execSQL("delete from record");
        database.close();
        querySearchRecord("");
    }

    //将该条搜索信息插入到手机数据库中
    private void insertWord(String word) {
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        database.execSQL("insert into record values(?,?)", new Object[]{null, word});
        database.close();
    }

    //查询存储在手机数据库中的搜索历史记录
    private void querySearchRecord(String keyword) {
        needToInsert = false;
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        Cursor cursor = database.rawQuery("select * from record where shearchword like ?", new String[]{
                "%" + keyword + "%"
        });
        // TODO: 2018/12/28 自定义是否将该字符串插入到数据库中（搜索历史记录中） 
        if (cursor.getCount() == 0) {
            needToInsert = true;
            setRecordViewVisibility(false);
        } else {
            setRecordViewVisibility(true);
        }
        keywordsList.clear();
        if (cursor.moveToFirst()) {
            do {
                String keywordString = cursor.getString(1);
                keywordsList.add(keywordString);
            } while (cursor.moveToNext());
        }

        keywordsRecordAdapter.notifyDataSetChanged();
        cursor.close();

//        Activity activity = (Activity) context;
//        activity.startManagingCursor(cursor);
/*        record.setAdapter(new SimpleCursorAdapter(context,
                android.R.layout.simple_expandable_list_item_1,
                cursor,
                new String[]{"shearchword"},
                new int[]{android.R.id.text1}

        ));*/
        database.close();
    }

    private void setRecordViewVisibility(boolean isShow) {
        if (isShow) {
            record.setVisibility(VISIBLE);
            deleteRecordTextView.setVisibility(VISIBLE);
        } else {
            record.setVisibility(GONE);
            deleteRecordTextView.setVisibility(GONE);
        }
    }

    //搜索历史的列表的适配器
    private class KeywordsRecordAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return keywordsList.size();
        }

        @Override
        public Object getItem(int position) {
            return keywordsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_search_view, null);
                viewHolder.textView = convertView.findViewById(R.id.tv_keyword);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            String keyword = keywordsList.get(position);
            if (!TextUtils.isEmpty(keyword)) {
                viewHolder.textView.setText(keyword);
            }
            return convertView;
        }

        class ViewHolder {
            TextView textView;
        }
    }

}
